package com.bjb.vr.common.handler;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.bjb.vr.common.constant.ThreadLocalConstant;
import com.bjb.vr.common.exception.CommonException;
import com.bjb.vr.common.result.BaseErrorCode;
import com.bjb.vr.common.utils.ThreadLocalUtil;
import com.bjb.vr.common.vo.UmsAccountVo;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * mybatisplus 自定义拦截器
 *
 * @version 1.0.0
 * @author: HuJingBo
 * @time: 2022/7/7 8:41
 */
@Slf4j
public class MybatisPlusTenantLineHandler implements TenantLineHandler {

    private static String[] defaultTables = {"BASE TABLE", "opt_area", "opt_help_doc", "res_content", "sys_tenant", "sync_data", "executed_sql", "sync_tenant", "ums_menu", "ums_opt_menu", "res_cus_content_authority", "res_content_authority", "res_dev_authority", "res_dev_authority_detail", "res_dictionary", "res_cascade", "sys_upgrade", "sys_upgrade_log", "sys_upgrade_dev_log"};

    @Override
    public Expression getTenantId() {
        UmsAccountVo umsAccountVo = (UmsAccountVo) ThreadLocalUtil.get(ThreadLocalConstant.USER_ACCOUNT_INFO);
        if (Objects.isNull(umsAccountVo)) {
            throw new CommonException(BaseErrorCode.ERROR_OBTAIN_TENANT_ID);
        }
        return new StringValue(umsAccountVo.getTenantId());
    }

    @Override
    public String getTenantIdColumn() {
        return TenantLineHandler.super.getTenantIdColumn();
    }

    @Override
    public boolean ignoreTable(String tableName) {
        // 无租户ID校验通过
        Boolean allow = (Boolean) ThreadLocalUtil.get(ThreadLocalConstant.NO_TENANT_ID_VERIFY);
        if (Objects.isNull(allow)) {
            log.error("\n除了【{}】这些表之外，其他表需要校验租户ID，或者使用【ThreadLocalUtil.set(ThreadLocalConstant.NO_TENANT_ID_VERIFY, true);】跳过租户验证！", Arrays.toString(defaultTables));
            return false;
        }
        if (allow) {
            return true;
        }
        List<String> collect = Arrays.stream(defaultTables).collect(Collectors.toList());
        return collect.contains(tableName);
    }
}
